<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input v-model="listQuery.columnValue" placeholder="请输入内容" style="width:300px;height:14px;padding-top:10px;padding-bottom:10px;margin-left:10px;margin-bottom:10px;">
        <el-select slot="prepend" v-model="listQuery.selectColumn" placeholder="请选择" style="width:100px;height:14px;">
          <el-option label="场所名称" value="sitename"/>
          <el-option label="建筑物名称" value="buildingname"/>
          <el-option label="监管单位名称" value="supervisorname"/>
          <el-option label="维保单位名称" value="maintainname"/>
          <el-option label="业主单位名称" value="proprietorname"/>
        </el-select>
      </el-input>
      <!--<el-input v-model="listQuery.keyword" style="width: 200px;" class="filter-item" placeholder="请输入菜单名称" @keyup.enter.native="handleFilter"/>-->
      <el-button v-waves v-if="btn_query" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button v-if="btn_add" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>
    <!--<el-button @click="changeRoute">123</el-button>-->
    <!--<tree-table :data="list" :async="false" :columns="columns" :expand-all="expandAll" border>-->
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column width="80" align="center" label="图标">
        <template slot-scope="scope">
          <img :src="scope.row.siteimageurl" style="height:auto;width:100%;">
        </template>
      </el-table-column>
      <!--<el-table-column width="80" align="center" label="场所号">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.siteid }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column width="150" align="center" label="场所名称">
        <template slot-scope="scope">
          <span>{{ scope.row.sitename }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column width="150" align="center" label="场所的url">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.siteurl }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column width="100" align="center" label="建筑名称">
        <template slot-scope="scope">
          <span>{{ scope.row.buildingname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="监管单位">
        <template slot-scope="scope">
          <span>{{ scope.row.supervisorname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="维保单位">
        <template slot-scope="scope">
          <span>{{ scope.row.maintainname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="业主单位">
        <template slot-scope="scope">
          <span>{{ scope.row.proprietorname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="btn_asset_manage" style="width:auto;" type="primary" size="mini" @click="handleAssetManage(scope.row)">
            {{ $t('table.assetManage') }}<!--资产管理-->
          </el-button>
          <el-button v-if="btn_device_manage" style="width:auto;" type="primary" size="mini" @click="handleDeviceManage(scope.row)">
            {{ $t('table.deviceManage') }}<!--传感器管理-->
          </el-button>
          <el-button v-if="btn_report_information" style="width:auto;" type="primary" size="mini" @click="handleReportInfo(scope.row)">
            {{ $t('table.reportInformation') }}<!-- 建筑物登记 -->
          </el-button>
          <el-button v-if="btn_edit" type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="btn_delete" type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>

    <!-- 增加及修改页 -->
    <el-dialog :title="textMap[dialogStatus]" :fullscreen="false" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 450px; margin-left:50px;">
        <template v-if="dialogStatus === 'update'">
          <el-form-item label="Id" prop="sitetoken">
            <el-input v-model="temp.sitetoken" :disabled="true" />
          </el-form-item>
        </template>
        <el-form-item label="场所名称" prop="sitename">
          <el-input v-model="temp.sitename"/>
        </el-form-item>
        <!--<el-form-item label="url" prop="siteurl">
          <el-input v-model="temp.siteurl"/>
        </el-form-item>-->
        <el-form-item label="场所图标" prop="siteimageurl">
          <el-input v-model="temp.siteimageurl" class="imageinput"/>
          <el-button size="medium" type="primary" class="uploadbutton" @click="activeTrigger">点击上传</el-button>
          <div v-if="dialogFormVisible">
            <el-upload
              ref="uploadTool"
              class="upload-demo"
              action=""
              :limit="1"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :http-request="getUploadAddress"
              list-type="picture">
              <button style="display: none" id="trigger"></button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="场所描述" prop="descriptor">
          <el-input v-model="temp.descriptor"/>
        </el-form-item>
        <el-form-item label="建筑名称" prop="buildingid">
          <el-select v-model="temp.buildingid" :disabled="dialogStatus === 'update'" class="filter-item select-width-100" placeholder="请选择">
            <el-option v-for="item in buildingOptions" v-if="!item.isUse || dialogStatus==='update'" :key="item.key" :label="item.value" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="监管单位" prop="supervisorid">
          <el-select v-model="temp.supervisorid" class="filter-item select-width-100" placeholder="请选择">
            <el-option v-for="item in supervisorOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="维保单位" prop="maintainor">
          <el-select v-model="temp.maintainor" class="filter-item select-width-100" placeholder="请选择">
            <el-option v-for="item in maintainorOptions" :key="item.key" :label="item.value" :value="item.key"/>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="业主单位" prop="proprietor">
          <el-select v-model="temp.proprietor" :disabled="dialogStatus === 'update'" class="filter-item select-width-100" placeholder="请选择">
            <el-option v-for="item in proprietorOptions" v-if="!item.isUse || dialogStatus==='update'" :key="item.key" :label="item.value" :value="item.key"/>
          </el-select>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button v-if="dialogStatus==='create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSite, deleteSite, fetchSiteList, updateSite } from '@/api/fire/site/site'
import { getMaintainorSelectItem } from '@/api/fire/maintainor/base'
import { selectLabelValue } from '@/api/fire/supervisor/base'
import { getProprietorItem } from '@/api/fire/proprietor/base'
import { getBuildingItem } from '@/api/fire/building/base'
import { uploadPic } from '@/api/fire/proprietor/monitor'
import waves from '@/directive/waves' // 水波纹指令
export default {
  name: 'SiteComponent',
  directives: {
    waves
  },
  data() {
    return {
      roleCode: '',
      expandAll: false,
      tableKey: 0,
      assetTableKey: 0,
      myAssetTableKey: 0,
      list: null,
      assetList: null,
      myAssetList: null,
      total: null,
      listLoading: true,
      treeSelectedOptions: [],
      maintainorOptions: [],
      supervisorOptions: [],
      proprietorOptions: [],
      buildingOptions: [],
      listQuery: {
        page: 1,
        limit: 10,
        selectColumn: '',
        columnValue: '',
        owner: ''
      },
      // sexOptions: getDictList('sex'),
      showReviewer: false,
      temp: {
        siteid: undefined,
        sitetoken: '',
        createtime: '',
        sitename: '',
        siteurl: '',
        siteimageurl: '',
        descriptor: '',
        buildingid: '',
        buildingname: '',
        supervisorid: '',
        supervisorname: '',
        maintainor: '',
        maintainname: '',
        proprietor: '',
        proprietorname: '',
        updatetime: ''
      },
      dialogFormVisible: false,
      dialogAssetFormVisible: false,
      dialogDeviceFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改场所',
        create: '添加场所'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        sitename: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 32, min: 5, message: '长度必须大于5小于32个字符', trigger: 'blur' }
        ],
        siteurl: [
          { required: false, type: 'url', max: 256, message: '请输入正确的url，并小于256个字符', trigger: 'blur' }
        ],
        descriptor: [
          { required: true, message: '请输入描述', trigger: 'blur' },
          { max: 256, min: 5, message: '长度必须大于5小于256个字符', trigger: 'blur' }
        ],
        buildingid: [{ required: true, message: '请选择建筑物', trigger: 'blur' }],
        supervisorid: [{ required: true, message: '请选择监管单位', trigger: 'blur' }],
        maintainor: [{ required: true, message: '请选择维保单位', trigger: 'blur' }],
        proprietor: [{ required: true, message: '请选择业主单位', trigger: 'blur' }]
      },
      downloadLoading: false,
      permissionTreeList: null,
      permissionQuery: {
        sort: '+id'
      },
      buttonInit: [
        {
          title: '查询',
          permission: 'list'
        },
        {
          title: '添加',
          permission: 'add'
        },
        {
          title: '更新',
          permission: 'update'
        },
        {
          title: '删除',
          permission: 'delete'
        },
        {
          title: '导出',
          permission: 'export'
        },
        {
          title: '导入',
          permission: 'import'
        }
      ],
      btn_query: false,
      btn_add: false,
      btn_edit: false,
      btn_delete: false,
      btn_asset_manage: false,
      btn_device_manage: false,
      btn_report_information: false,
      // 文件上传↓↓
      fileList: [],
      file: null
    }
  },
  created() {
    // console.log(this.$refs)
    // this.$refs.reportInfo.initFrom()
    this.getList()
    // this.changeRoute()
    this.queryMaintainorOptions()
    this.querySupervisorOptions()
    this.queryProprietorOptions()
    this.queryBuildingOptions()
    const roles = this.$store.state.user.roles
    for (const role in roles) {
      console.log(role + ':' + roles[role])
      if (roles[role] === 'admin') {
        this.roleCode = roles[role]
        break
      }
      if (roles[role] === 'supervisor') {
        this.roleCode = roles[role]
        break
      }
      if (roles[role] === 'proprietor') {
        this.roleCode = roles[role]
        break
      }
      if (roles[role] === 'maintainor') {
        this.roleCode = roles[role]
        break
      }
    }
    console.log(this.roleCode)
    this.btn_query = this.checkPermission([this.roleCode + ':site:list'])
    this.btn_add = this.checkPermission([this.roleCode + ':site:add'])
    this.btn_edit = this.checkPermission([this.roleCode + ':site:update'])
    this.btn_delete = this.checkPermission([this.roleCode + ':site:delete'])
    this.btn_asset_manage = this.checkPermission([this.roleCode + ':site:assetManage'])
    this.btn_device_manage = this.checkPermission([this.roleCode + ':site:deviceManage'])
    this.btn_report_information = this.checkPermission([this.roleCode + ':site:reportInformation'])
  },
  methods: {
    changeRoute() {
      this.$store.dispatch('ChangeRoute')
      this.$store.commit('BACK_VISIBLE', true)
    },
    getList() {
      this.listLoading = true
      fetchSiteList(this.listQuery).then(response => {
        this.list = response.data.context.records
        this.total = response.data.context.total
        this.listLoading = false
      })
      // 刷新可能变动的下拉选数据
      this.queryBuildingOptions()
      this.queryProprietorOptions()
    },
    changeRequireAuth() {

    },
    handleFilter() {
      this.getList()
    },
    resetTemp() {
      this.temp = {
        siteid: undefined,
        sitetoken: '',
        createtime: '',
        sitename: '',
        siteurl: '',
        siteimageurl: '',
        descriptor: '',
        buildingid: '',
        buildingname: '',
        supervisorid: '',
        supervisorname: '',
        maintainor: '',
        maintainname: '',
        proprietor: '',
        proprietorname: '',
        updatetime: ''
      }
      this.treeSelectedOptions.length = 0
    },
    handleCreate() {
      this.resetTemp()
      this.changeRequireAuth()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // 清除上传列表
      this.$refs.uploadTool.clearFiles()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData: function() {
      // 预处理提交的数据
      for (const optionObj in this.buildingOptions) {
        if (this.buildingOptions[optionObj].key === this.temp.buildingid) {
          this.temp.buildingname = this.buildingOptions[optionObj].value
        }
      }
      for (const optionObj in this.supervisorOptions) {
        if (this.supervisorOptions[optionObj].value === this.temp.supervisorid) {
          this.temp.supervisorname = this.supervisorOptions[optionObj].label
        }
      }
      for (const optionObj in this.maintainorOptions) {
        if (this.maintainorOptions[optionObj].key === this.temp.maintainor) {
          this.temp.maintainname = this.maintainorOptions[optionObj].value
        }
      }
      for (const optionObj in this.proprietorOptions) {
        if (this.proprietorOptions[optionObj].key === this.temp.proprietor) {
          this.temp.proprietorname = this.proprietorOptions[optionObj].value
        }
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // if (this.temp.parentIds !== undefined && this.temp.parentIds !== '') {
          //   this.temp.parentIds.length = 0
          // }
          addSite(this.temp).then((response) => {
            const data = response.data
            if (data.status === '0') {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: data.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetTemp()
      this.temp = Object.assign({}, row) // copy obj
      this.changeRequireAuth()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // 清除上传列表
      this.$refs.uploadTool.clearFiles()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateSite(tempData).then((response) => {
            const data = response.data
            if (data.status === '0') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: data.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认要删除站点么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSite(row.sitetoken).then(response => {
          const data = response.data
          if (data.status === '0') {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          } else {
            this.$notify({
              title: '失败',
              message: data.message,
              type: 'error',
              duration: 2000
            })
          }
        })
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleAssetManage(row) {
      this.$store.dispatch('SET_SITEID', row.siteid)
      this.$router.push({ path: '/asset/index' })
    },
    handleDeviceManage(row) {
      console.log('submit!')
      this.$store.dispatch('SET_SITEID', row.siteid)
      this.$router.push('/device')
    },
    handleReportInfo(row) {
      this.$store.dispatch('SET_SITEID', row.siteid)
      this.$router.push({ path: '/site/reportInfo' })
    },
    queryMaintainorOptions() {
      getMaintainorSelectItem().then(response => {
        if (response.data.status === '0') {
          this.maintainorOptions = response.data.context
        }
      })
    },
    querySupervisorOptions() {
      selectLabelValue().then(response => {
        if (response.data.status === '0') {
          this.supervisorOptions = response.data.context
        }
      })
    },
    queryProprietorOptions() {
      getProprietorItem().then(response => {
        if (response.data.status === '0') {
          this.proprietorOptions = response.data.context
        }
      })
    },
    queryBuildingOptions() {
      getBuildingItem().then(response => {
        if (response.data.status === '0') {
          this.buildingOptions = response.data.context
        }
      })
    },
    // 文件上传↓↓
    getUploadAddress(param) {
      const formData = new FormData()
      formData.append('file', param.file, param.file.name)
      uploadPic(formData).then(response => {
        this.temp.siteimageurl = response.data.context
      })
    },
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      this.temp.siteimageurl = ''
    },
    activeTrigger(){
      document.getElementById("trigger").click();
    },
  }
}
</script>
<style>
  .select-width-100{
    width: 100%;
  }
  .imageinput{
    width: 73%;
    display: inline-block;
  }
  .uploadbutton{
    width: 25%;
    display: inline-block;
    padding: 10px 0px;
  }
  .el-upload{
    display: none;
  }
</style>
